package com.common.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static final String secretc = "K3Jz34joZkQT05TDGTrsqk9TTjc6IZHa3Wa+oZCdZUaUMhG86GqbJIzD+J9xVRvPccVKn66Al4nV5ufMkgo5qQ=="; // 生成安全的密钥



    public static String generateToken(Long userId) {
        Date now = new Date();
        SecretKey key = Keys.hmacShaKeyFor(secretc.getBytes()); // 使用给定的密钥字节数组创建密钥

        return Jwts.builder()
                .setSubject(userId+"")
                .setIssuedAt(now)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
    }

    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretc.getBytes())
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretc.getBytes()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
